﻿using Module=Autofac.Module;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Autofac;
using Ruanmou.Context;
using Microsoft.EntityFrameworkCore;
using Ruanmou.Repository;
using Ruanmou.IRepository;
using Ruanmou.Service;
using Ruanmou.IService;

namespace Ruanmou.Autofac
{

    /// <summary>
    /// 依赖注入
    /// </summary>
    public class RuanmouAutofac:Module
    {
        protected override void Load(ContainerBuilder containerBuilder)
        {
            //获取需要注入的程序集名称
            var IServices = GetAssemblyByName("Ruanmou.IService");
            var Services = GetAssemblyByName("Ruanmou.Service");
            var IRepository = GetAssemblyByName("Ruanmou.IRepository");
            var Repository = GetAssemblyByName("Ruanmou.Repository");

            //根据名称约定（服务层的接口和实现均以Service结尾），实现服务接口和服务实现的依赖
            containerBuilder.RegisterAssemblyTypes(IServices, Services)
              .Where(t => t.Name.EndsWith("Service"))
              .AsImplementedInterfaces();

            //根据名称约定（数据访问层的接口和实现均以Repository结尾），实现数据访问接口和数据访问实现的依赖
            containerBuilder.RegisterAssemblyTypes(IRepository, Repository)
              .Where(t => t.Name.EndsWith("Repository"))
              .AsImplementedInterfaces();

            //注册DbContext
            containerBuilder.RegisterType<RuanmouContext>().As<DbContext>();
           
        }
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
    }
}
